<?php

class UsersController extends AppController {

	const REGISTER_NEWSLETTER = 'newsletter';

	var $name = 'Users';

	protected $_allowActions = array('register_newsletter', 'system_login');

	public function register_newsletter(){
		$email = $this->params['form']['email'];
		// validate email
		Utils::loadModels($this, array('User'));
		$this->User->create();
		$this->User->set(array(
			'email' => $email,
			'news_subscription' => User::ENUM_YES,
			'status' => User::STATUS_INACTIVE,
			'password' => sha1('')
		));
		$id = $this->User->getLastInsertId();
		if(!$this->User->validates()){
			$this->response['status'] = 1;
			$this->response['message'] = implode('<br/>', $this->User->validationErrors);
		} else {
			$this->User->save();
			$this->response['status'] = 0;
		}
		$this->sendAjax();
	}

	public function login(){
		// has logined, terminate here
		if($this->Auth->user('id')){
			$this->redirect($this->Auth->redirect());
		}
		if($this->isPost()){
			Utils::loadModels($this, array('User'));
			$loginOk = false;
			if(!empty($_POST['data']['User']['password'])){
				$rawPassword = $_POST['data']['User']['password'];
			} else {
				$rawPassword = '';
			}
			$user = $this->User->findByEmail($this->data['User']['email']);
			if(empty($user)){
				// register him
				$this->User->create();
				$this->data['User']['email'] = strtolower($this->data['User']['email']);
				$this->data['User']['password'] = sha1($rawPassword);
				$this->data['User']['status'] = User::STATUS_ACTIVE;
				$this->User->set($this->data);
				if(!$this->User->validates()){
					$message = implode('</br>', $this->User->validationErrors);
					$this->Session->setFlash($message, 'auth');
				} else {
					$this->User->save();
					$this->Auth->login($this->data);
					$this->redirect($this->Auth->redirect());
				}
			} else {
				// set password if his password is empty
				$hasNoPassword = $user['User']['password'] == sha1('');
				if($hasNoPassword){
					$user['User']['password'] = sha1($rawPassword);
					$user['User']['status'] = User::STATUS_ACTIVE;
					$this->User->save($user, false);
					$loginOk = $this->Auth->login($user);
					$this->redirect($this->Auth->redirect());
				}
			}
		}
		$this->data['User']['password'] = '';
	}

	public function forgetpassword(){
		Utils::loadModels($this, array('User'));
    	if(!empty($this->data)){
    		$user = $this->User->find('first' , array('conditions' => array(
    			'User.email' => trim($this->data['User']['email']),
    			'User.status' => User::STATUS_ACTIVE
    		)));
			if(!empty($user)){
				$user['User']['tmp_password'] = $this->_randPassword();
				$this->User->id = $user['User']['id'];
				$this->User->saveField('password', sha1($user['User']['tmp_password']));
				$this->_sendResetPasswordMail($user);
				$this->setFlash('Email đã được gửi cho bạn. Vui lòng kiểm tra mật khẩu mới.', array( 'class' => 'success' ) );
			}else {
				$this->setFlash('Email của bạn chưa tồn tại trong hệ thống.', array( 'class' => 'error' ) );
			}
    	}
    }

	public function changepassword(){
		if(!empty($this->data)){
			$user = $this->User->findByEmail($this->Auth->user('email'));
			if(!empty($user)){
				$this->User->set($this->data);
				unset($this->User->validate['email']);
				$passwordsMatched = !empty($this->data['User']['confirm_password']) ? $this->data['User']['password'] == sha1($this->data['User']['confirm_password']) : false;
				if ($passwordsMatched) {
					$this->User->id = $user['User']['id'];
					$this->User->saveField('password', $this->data['User']['password']);
					$user = $this->User->findById($user['User']['id']);
					$this->Auth->login($user);
					$this->setFlash('Mật khẩu đã thay đổi', array( 'class' => 'success' ) );
				} else {
					$errors = $this->User->invalidFields();
					$this->data['User']['password'] = '';
					$this->setFlash( 'Phải nhập mật khẩu. Mật khẩu và mật khẩu đối chiếu phải trùng nhau.' );
				}
			}
		}
		$this->data['User']['password'] = '';
    }

	private function _sendResetPasswordMail($user) {
		Utils::loadComponents($this, array('Mail'));
		$to = $user['User']['email'];
		$subject = 'youbrainy.com - Mật khẩu mới';
		$template = 'reset_password';
		$this->Mail->sendMail($to, $subject, $template, array('user' => $user));
	}

	private function _randPassword(){
		return substr(sha1(uniqid()), 0, 10);
	}

	public function logout() {
		$this->redirect($this->Auth->logout());
	}

	public function system_login(){
		if($this->isPost()){
			Utils::loadModels($this, array('SystemUser'));
			$email = $this->data['User']['email'];
			$user = $this->SystemUser->findByEmail($email);
			if(empty($user)){
				$this->Session->setFlash('Login failure', 'auth');
			} else {
				if($user['SystemUser']['password'] != sha1($this->data['User']['password'])){
					$this->Session->setFlash('Login failure, wrong password', 'auth');
				} else {
					$this->Auth->login($user);
					$this->redirect($this->Auth->redirect());
				}
			}
		}
	}
}